package com.webex.ta.hydra.gui.table.undo;

import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.core.CommandVisitor;
import com.webex.ta.hydra.gui.table.HydraTable;
import com.webex.ta.hydra.gui.table.HydraTableModel;

import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-16
 * Time: 15:31:04
 */
public class ChangeEdit extends AbstractUndoableEdit {
    private HydraTableModel model;
    private Command oldValue, newValue;

    public ChangeEdit(HydraTableModel model, Command oldValue, Command newValue) {
        this.model = model;
        this.oldValue = oldValue;
        this.newValue = newValue;
    }

    @Override
    public void undo() throws CannotUndoException {
        super.undo();
        Finder finder = new Finder(oldValue);
        model.getRoot().traverse(finder);
        if (finder.result != null) {
            finder.result.copyAttributesFrom(oldValue);
        }
        HydraTable.checkMacroLoad(newValue, oldValue);
        model.fireTableDataChanged();
    }

    @Override
    public void redo() throws CannotRedoException {
        super.redo();
        Finder finder = new Finder(newValue);
        model.getRoot().traverse(finder);
        if (finder.result != null) {
            finder.result.copyAttributesFrom(newValue);
        }
        HydraTable.checkMacroLoad(oldValue, newValue);
        model.fireTableDataChanged();
    }



    private class Finder implements CommandVisitor {
        private Command target;

        private Command result = null;

        public Finder(Command target) {
            this.target = target;
        }

        public void visit(Command cmd) {
            if (cmd.getUuid() == target.getUuid()) {
                result = cmd;
            }
        }
    }
}
